//! 认证中间件
//! # Example
//! ```
//! use tower::ServiceBuilder;
//! use axum_lib::middleware::auth_middleware::AuthLayer;
//! ServiceBuilder::new()
//!     .layer(AuthLayer)
//! ```
use crate::middleware::PinBox;
use crate::R;
use axum::response::IntoResponse;
use axum::{
    extract::Request,
    response::Response,
};
use std::task::{Context, Poll};
use tower::{Layer, Service};

#[derive(Clone)]
pub struct AuthLayer;

impl<S> Layer<S> for AuthLayer {
    type Service = AuthMiddleware<S>;

    fn layer(&self, inner: S) -> Self::Service {
        AuthMiddleware { inner }
    }
}

#[derive(Clone)]
pub struct AuthMiddleware<S> {
    inner: S,
}

impl<S> Service<Request> for AuthMiddleware<S>
where
    S: Service<Request, Response=Response> + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = PinBox<Self::Response, Self::Error>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request) -> Self::Future {
        let auth = request.headers()
            .get("token")
            .and_then(|header| header.to_str().ok())
            .is_some_and(|token| token == "token");
        let future = self.inner.call(request);
        Box::pin(async move {
            if auth {
                let response = future.await?;
                Ok(response)
            } else {
                Ok(R::<()>::token_fail().into_response())
            }
        })
    }
}